<script>
import {
    ElForm,
    ElFormItem,
    ElInput,
    ElRadio,
    ElRadioGroup,
    ElButton,
    ElDatePicker,
    ElMessage
} from 'element-plus';

import moment from 'moment';

export default {
  name: 'student-list',
  components: {
    ElForm,
    ElFormItem,
    ElInput,
    ElRadio,
    ElRadioGroup,
    ElButton,
    ElDatePicker,
    ElMessage
  },
  data() {
    return {
      student: {
        name: '',
        gender: '',
        birthdate: '',
        hometown: ''
      }
    };
  },
  methods: {
    add() {
      const url = '/kaifamiao/student';
      const entity = {...this.student};
      entity.birthdate = moment(entity.birthdate).format('YYYY-MM-DD');
      // 发起POST请求并通过请求体发送数据
      this.axios.post(url, entity)
                .then( resp => {
                  let { success, message } = resp.data;
                  if(success) {
                    // 编程式导航
                    this.$router.push('/student/list');
                    return;
                  }
                  ElMessage({type:'warning', message});
                }).catch( reason =>{
                  if( reason instanceof Error ) {
                    ElMessage.error('添加失败');
                  }
                });
    }
  }
}
</script>

<template>
  <div class="student-add">
    <h3>添加学生</h3>
    <el-form :model="student" label-width="120px">
        <el-form-item label="姓名">
            <el-input v-model="student.name"></el-input>
        </el-form-item>
        <el-form-item label="性别">
            <el-radio-group v-model="student.gender">
                <el-radio label="male" size="large">靓仔</el-radio>
                <el-radio label="female" size="large">靓妹</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期">
            <el-date-picker v-model="student.birthdate" type="date" :editable="false" />
        </el-form-item>
        <el-form-item label="籍贯">
            <el-input v-model="student.hometown"></el-input>
        </el-form-item>
        <el-form-item label="">
            <el-button type="primary" @click="add">添加</el-button>
        </el-form-item>
    </el-form>
  </div>
</template>